package com.usernet.product.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.sql.Timestamp;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.usernet.product.comm.BaseAction;
import com.usernet.product.entity.Error;
import com.usernet.product.entity.Software;
import com.usernet.product.utils.ProductConfig;

public class DownAction extends BaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);

		File file = new File(ProductConfig.realPath + "upload/software/"
				+ software.getDownload());
		if (file.exists()) {
			response.setHeader("content-disposition", "attachment; filename="
					+ URLEncoder.encode(software.getName() + "_"
							+ software.getVersion(), "UTF-8") + ".apk");
			FileInputStream in = org.apache.commons.io.FileUtils
					.openInputStream(file);
			ServletOutputStream sout = response.getOutputStream();
			org.apache.commons.io.IOUtils.copy(in, sout);
			sout.close();
			in.close();
			sout = null;
			in = null;
		} else {
			Error error = new Error();
			error.setSoftware(software);
			error.setStatus(0);
			error.setUsers(null);
			error.setInfo("资源文件不存在");
			error.setTime(new Timestamp(System.currentTimeMillis()));
			errorDao.save(error);
		}
		return null;
	}
}
